<template>
  <div class="tab-page-main">
    <el-tabs v-model="other.tabActive" type="card" class="page-tabs">
      <el-tab-pane label="机器人列表" :name="0">
        <div class="tab-page-content">
          <div class="form py-[15px] flex items-center">
            <el-input class="!w-[140px]" v-model="searchForm.Name" placeholder="请输入机器人名称" />
            <el-button class="!ml-[10px]" type="primary" @click.stop="search">搜索</el-button>
            <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
            <div class="flex items-center ml-[10px]">
              <span class="mr-[10px]">状态: </span>
              <el-switch
                :model-value="searchForm.Status"
                inline-prompt
                size="large"
                active-text="全部开启"
                inactive-text="全部关闭"
                :active-value="1"
                :inactive-value="0"
                @change="handleAllStatus"
              />
            </div>
          </div>
          <div class="grow-[1] h-0">
            <el-table
              scrollbar-always-on
              v-loading="state.loading"
              :data="list"
              height="100%"
              border
              stripe
              fit
            >
              <template #empty>
                <ui-empty />
              </template>
              <el-table-column align="center" prop="avatar" label="头像" width="60">
                <template #default="{ row }: TableItem">
                  <div class="flex items-center justify-center">
                    <avatar :size="30" :src="row.Avatar" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="Uid" align="center" label="UID" width="70" />
              <el-table-column prop="Name" align="center" label="名称" show-overflow-tooltip>
                <template #default="{ row }: TableItem">
                  {{ row.Name || "--" }}
                </template>
              </el-table-column>
              <el-table-column prop="Nickname" align="center" label="昵称" show-overflow-tooltip>
                <template #default="{ row }: TableItem">
                  {{ row.Nickname || "--" }}
                </template>
              </el-table-column>
              <el-table-column prop="Coin" align="center" label="余额" min-width="120">
                <template #default="{ row }: TableItem">
                  <ui-amount :num="formatCurrency(row.Coin)" />
                </template>
              </el-table-column>
              <el-table-column
                prop="MiniBet"
                align="center"
                label="最小下注金额"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column
                prop="MaxBet"
                align="center"
                label="最大下注金额"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column prop="Status" align="center" label="状态" width="80">
                <template #default="{ row }: TableItem">
                  <el-dropdown
                    placement="bottom"
                    @command="(e: number) => handleChangeStatus(row, e)"
                  >
                    <el-button v-if="row.Status == 1" type="success" size="small">开启</el-button>
                    <el-button v-else type="danger" size="small">关闭</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :disabled="row.Status == 1" :command="1">
                          开启
                        </el-dropdown-item>
                        <el-dropdown-item :disabled="row.Status == 0" :command="0">
                          关闭
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" align="center">
                <template #default="{ row }: TableItem">
                  <el-button type="primary" size="small" @click="handlePoint(row)">
                    分数操作
                  </el-button>
                  <el-button type="success" size="small" @click="handleEdit(row)">编辑</el-button>
                  <el-button type="danger" size="small" @click="handleDel(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="flex justify-end my-[10px] mx-[15px]">
            <ui-pagination
              :total="state.total"
              v-model:pageSize="state.pageSize"
              v-model:currentPage="state.page"
              @current-change="getData"
            ></ui-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="添加机器人" :name="1">
        <div class="tab-page-content !px-0">
          <el-scrollbar
            always
            class="w-full h-full overflow-hidden px-[15px] box-border"
            ref="scrollbarRef"
          >
            <div class="form my-[15px]">
              <section class="add-item flex">
                <article><span class="required">✲</span><span>头像</span></article>
                <article>
                  <avatar upload :size="30" :src="form.Avatar"></avatar>
                  <system-img @update="handleSetAvatar">
                    <el-button class="mx-[10px]" type="primary" size="small">系统头像</el-button>
                  </system-img>
                  <upload-img @update="handleSetAvatar">
                    <el-button type="primary" size="small">上传头像</el-button>
                  </upload-img>
                </article>
              </section>
              <section class="add-item flex">
                <article><span class="required">✲</span><span>机器人名称</span></article>
                <article>
                  <el-input v-model="form.Name" placeholder="请输入机器人名称" />
                  <el-button
                    @click="handleRobotName"
                    class="ml-[5px]"
                    type="primary"
                    icon="Refresh"
                    circle
                  />
                </article>
              </section>
              <section class="add-item flex">
                <article>
                  <span class="required">✲</span>
                  <span>机器人昵称</span>
                </article>
                <article>
                  <el-input v-model="form.Nickname" placeholder="请输入机器人名称" />
                  <el-button
                    @click="handleRobotNickname"
                    class="ml-[5px]"
                    type="primary"
                    icon="Refresh"
                    circle
                  />
                </article>
              </section>
              <section class="add-item flex">
                <article>状态</article>
                <article>
                  <el-switch
                    v-model="form.Status"
                    inline-prompt
                    size="large"
                    active-text="开启"
                    inactive-text="关闭"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </article>
              </section>
              <section class="add-item flex">
                <article>
                  <span class="required">✲</span>
                  <el-select class="custom-select" v-model="form.DepositType">
                    <el-option label="自动上分固定金额" :value="1" />
                    <el-option label="自动上分随机金额" :value="2" />
                  </el-select>
                  <el-tooltip effect="dark" placement="top">
                    <template #content>
                      <p>
                        <b>自动上分固定金额：</b>可以设置多个，用井号 #
                        分隔，自动上分金额最好不要大于自动下分警戒线。根据当前设定的自动上分积分，取一个金额去上分，上分后托积分大于上分警戒线。
                      </p>
                      <div>
                        <p>
                          <b>自动上分随机金额：</b>可以设置范围区间，用井号 #
                          分隔，自动上分随机金额范围最好不要大于自动下分警戒线。根据当前设定的自动上分随机金额，取随机金额范围内的10整倍去上分，上分后托积分大于上分警戒线。
                        </p>
                      </div>
                    </template>
                    <el-icon class="!text-[18px] ml-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </article>
                <article>
                  <el-input v-model="form.DepositAmount" placeholder="200#300#500#800#1000" />
                </article>
              </section>
              <section class="add-item flex">
                <article>
                  <span class="required">✲</span>
                  <el-select class="custom-select" v-model="form.WithdrawType">
                    <el-option label="自动下分固定金额" :value="1" />
                    <el-option label="自动下分随机金额" :value="2" />
                  </el-select>
                  <el-tooltip effect="dark" placement="top">
                    <template #content>
                      <p>
                        <b>自动下分固定金额：</b>可以设置多个，用井号 #
                        分隔，自动下分金额最好不要大于自动上分警戒线。根据托当前积分，取一个金额去下分，下分后托积分小于下分警戒线且大于自动上分警戒线。
                      </p>
                      <div>
                        <p>
                          <b>自动下分随机金额：</b>可以设置范围区间，用井号 #
                          分隔，自动下分随机金额范围最好不要大于自动上分警戒线。根据当前设定的自动下分随机金额，取随机金额范围内的10整倍去下分，下分后托积分小于下分警戒线且大于自动上分警戒线
                        </p>
                      </div>
                    </template>
                    <el-icon class="!text-[18px] ml-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </article>
                <article>
                  <el-input v-model="form.WithdrawAmount" placeholder="200#300#500#800#1000" />
                </article>
              </section>
              <section class="add-item flex">
                <article>
                  <span class="required">✲</span><span>最小下注金额</span>
                  <el-tooltip content="托每一笔注单下注的最小金额" effect="dark" placement="top">
                    <el-icon class="!text-[18px] ml-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </article>
                <article>
                  <el-input type="number" v-model="form.MiniBet" placeholder="请输入最小下注金额" />
                </article>
              </section>
              <section class="add-item flex">
                <article>
                  <span class="required">✲</span>
                  <span>最大下注金额</span>
                  <el-tooltip
                    content="托每一笔注单下注的最大金额，最大下注金额最好不要大于自动上分警戒线"
                    effect="dark"
                    placement="top"
                  >
                    <el-icon class="!text-[18px] ml-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </article>
                <article>
                  <el-input type="number" v-model="form.MaxBet" placeholder="请输入最大下注金额" />
                </article>
              </section>
              <section class="add-item last-item flex">
                <article><span>下注游戏</span></article>
                <article>
                  <div v-for="item in games" :key="item.LotteryId" class="game">
                    <span>{{ item.Name }}</span>
                    <el-switch
                      size="large"
                      v-model="item.Checked"
                      @change="handelSwitch(item.Checked!, item.LotteryId)"
                    />
                  </div>
                </article>
              </section>
              <section class="flex justify-end py-[10px]">
                <el-button
                  :disabled="other.loading"
                  :loading="other.loading"
                  type="primary"
                  @click="handleAdd"
                  >添加机器人</el-button
                >
              </section>
            </div>
          </el-scrollbar>
        </div>
      </el-tab-pane>
    </el-tabs>
    <point-dialog
      ref="pointDialogRef"
      :uid="currentData?.Uid"
      :username="currentData?.Name"
      type="robot"
      @update="getData"
    />
    <!-- 编辑机器人 -->
    <robot-info-dialog ref="robotInfoDialogRef" :data="currentData" @update="getData" />
  </div>
</template>
<script setup lang="ts">
import PointDialog from "./components/point-dialog.vue";
import RobotInfoDialog from "./components/robot-info-dialog.vue";

import { useList } from "@/hooks/useList";
import {
  reqRobotAdd,
  reqRobotAllStatus,
  reqRobotDel,
  reqRobotList,
  reqRobotStatus
} from "@/api/user";
import { formatCurrency, generateNickname, generateUsername } from "@/utils/common";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { cloneDeep } from "lodash-es";
import { storeToRefs } from "pinia";
import { useGameStore } from "@/store/modules/game";
import { GameCategory } from "@/enums";

interface TableItem {
  row: RobotMo;
}

const other = reactive({
  loading: false,
  tabActive: 0
});
const searchForm = reactive({
  Name: "",
  Status: 0
});
const defauleForm = {
  Name: generateUsername(),
  Nickname: generateNickname(),
  Avatar: "",
  Status: 1,
  DepositType: 1,
  WithdrawType: 1,
  DepositAmount: "200#300#500#800#1000#2000",
  WithdrawAmount: "200#300#500#800#1000#2000",
  MiniBet: "10",
  MaxBet: "200",
  BetGame: ""
};
const form = reactive({ ...defauleForm });
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const currentData = ref<RobotMo | null>(null);
const games = ref(gameTotal.value.filter(item => item.CategoryId !== GameCategory.lhc));

const robotInfoDialogRef = ref();
const pointDialogRef = ref();

const getParams = () => {
  const params: any = {};
  if (searchForm.Name) {
    params.Name = searchForm.Name;
  }
  return params;
};

const { state, list, getData, search } = useList<RobotMo, { Name: string }>(
  reqRobotList,
  getParams
);

const handleRefresh = () => {
  searchForm.Name = "";
  search();
};

const handelSwitch = (flag: boolean, id: number) => {
  let betGame = form.BetGame ? form.BetGame.split(",") : [];
  if (flag) {
    betGame.push(String(id));
  } else {
    betGame = betGame.filter(item => Number(item) !== id);
  }
  form.BetGame = betGame.length > 0 ? betGame.join(",") : "";
};

// 修改状态
const handleChangeStatus = async (row: RobotMo, key: number) => {
  try {
    state.loading = true;
    await reqRobotStatus(row.Id, key);
    message.success("修改状态成功");
    state.loading = false;
    row.Status = key;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const handleSetAvatar = (img: string) => {
  form.Avatar = img;
};

// 分数操作
const handlePoint = (row: RobotMo) => {
  currentData.value = row;
  nextTick(() => {
    pointDialogRef.value.open();
  });
};

// 编辑
const handleEdit = (row: RobotMo) => {
  currentData.value = row;
  nextTick(() => {
    robotInfoDialogRef.value.open();
  });
};

// 修改全部机器人状态
const handleAllStatus = (status: number) => {
  ElMessageBox.confirm(status == 1 ? `是否【开启】所有机器人` : "是否【关闭】所有机器人", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqRobotAllStatus(status);
          message.success(status == 1 ? "全部开启成功" : "全部关闭成功");
          searchForm.Status = status;
          getData();
          done(); // 操作成功后关闭对话框
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

// 删除
const handleDel = (row: RobotMo) => {
  ElMessageBox.confirm(`是否进行【删除】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqRobotDel(row.Id);
          message.success("删除成功");
          getData();
          done(); // 操作成功后关闭对话框
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

const handleRobotName = () => {
  form.Name = generateUsername();
};

const handleRobotNickname = () => {
  form.Nickname = generateNickname();
};

function validateFormat(input: string) {
  const regex = /^(\d+#)+\d+$/;
  return regex.test(input);
}

// 添加机器人
const handleAdd = async () => {
  try {
    if (!form.Avatar) {
      return message.warning("请上传头像");
    }
    if (!form.Name) {
      return message.warning("请输入机器人名称");
    }
    if (!form.Nickname) {
      return message.warning("请输入机器人昵称");
    }
    if (form.DepositAmount == "") {
      return message.warning("请输入自动上分金额");
    }
    if (!validateFormat(form.DepositAmount)) {
      return message.warning("请输入正确的自动上分金额");
    }
    if (form.WithdrawAmount == "") {
      return message.warning("请输入自动下分金额");
    }
    if (!validateFormat(form.WithdrawAmount)) {
      return message.warning("请输入正确的自动下分金额");
    }
    if (form.MiniBet == "") {
      return message.warning("请输入最小下注金额");
    }
    if (form.MaxBet == "") {
      return message.warning("请输入最大下注金额");
    }
    if (!form.BetGame) {
      return message.warning("请选择下注游戏");
    }
    other.loading = true;
    await reqRobotAdd({
      ...form,
      DepositType: Number(form.DepositType),
      WithdrawType: Number(form.WithdrawType),
      MiniBet: Number(form.MiniBet),
      MaxBet: Number(form.MaxBet),
      BetGame: form.BetGame.split(",")
        .map(num => `{${num}}`)
        .join("")
    });
    other.loading = false;
    message.success("添加机器人成功");
    handleRefresh();
    Object.assign(form, defauleForm); // 用默认状态覆盖当前状态
    other.tabActive = 0;
  } catch (error) {
    other.loading = false;
    console.log(error);
  }
};

watch(
  () => gameTotal.value,
  val => {
    games.value = cloneDeep(val.filter(item => item.CategoryId !== GameCategory.lhc));
  }
);

watch(
  () => form.DepositType,
  val => {
    if (val == 1) {
      form.DepositAmount = "200#300#500#800#1000#2000";
    } else {
      form.DepositAmount = "200#2000";
    }
  }
);

watch(
  () => form.WithdrawType,
  val => {
    if (val == 1) {
      form.WithdrawAmount = "200#300#500#800#1000#2000";
    } else {
      form.WithdrawAmount = "200#2000";
    }
  }
);

onMounted(() => {
  getData();
  gameStore.actionGameList();
});
</script>
<style lang="scss" scoped>
.add-item {
  border: 1px solid #ddd;
  border-bottom: 0;
  justify-content: space-between;
  article:first-child {
    width: 200px;
    padding: 0 15px;
    border-right: 1px solid #ddd;
    .required {
      margin-right: 2px;
    }
  }
  article:last-child {
    padding: 5px 10px;
    flex-grow: 1;
    width: 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  article {
    display: flex;
    align-items: center;
  }
  .game {
    display: flex;
    align-items: center;
    width: 25%;
    margin-bottom: 5px;
    > span {
      width: 100px;
      margin-left: 5px;
      font-size: 13px;
    }
  }
  :deep() {
    .el-input,
    .el-textarea {
      --el-input-bg-color: #f9f9f9;
    }
    .el-input {
      width: 400px !important;
    }
    .el-select__selected-item {
      font-size: 14px;
    }
  }
}
.last-item {
  border-bottom: 1px solid #ddd;
}
:deep() {
  .el-tabs--card {
    .el-tabs__header {
      .el-tabs__item {
        font-size: 15px !important;
      }
      .el-tabs__item.is-active {
        font-weight: normal !important;
      }
    }
  }
}
</style>
